package com.jian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jian.common.ErrorCode;
import com.jian.content.User;
import com.jian.content.UserContent;
import com.jian.domain.Entrust;
import com.jian.exception.BusinessException;
import com.jian.mapper.EntrustMapper;
import com.jian.requests.CourierRequestBody;
import com.jian.responses.EntrustResponse;
import com.jian.service.EntrustService;
import com.jian.utils.RedisToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author 18214
 * @description 针对表【entrust】的数据库操作Service实现
 * @createDate 2022-06-03 08:22:06
 */
@Service
public class EntrustServiceImpl extends ServiceImpl<EntrustMapper, Entrust>
        implements EntrustService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean addEntrustOnce(Entrust entrust) {
        LinkedHashMap map = RedisToken.readFromRedis(redisTemplate, entrust.getToken());
        if (map == null) {
            throw new BusinessException(ErrorCode.NO_AUTH, "该用户token不存在");
        }
        Long userID;
        try {
            String str_user = map.get("id").toString();
            userID = Long.parseLong(str_user);
            if (userID <= 0) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "该用户的id错误");
            }
        } catch (NumberFormatException e) {
            throw new BusinessException(
                    ErrorCode.SYSTEM_ERROR, "该用户的id解析失败原因是:" + e.getMessage());
        }
        entrust.setUId(userID);
        return save(entrust);
    }

    @Override
    public List<EntrustResponse> getEntrustsFromRule(String token) {
        // 获取当前用户的id 与 该用户的权限
        User user = RedisToken.readFromRedis(redisTemplate, token, User.class);
        int rule = userRule(token);
        if (rule == UserContent.NOT_LOGIN)
            throw new BusinessException(ErrorCode.NO_AUTH, "该用户未登录!");

        // 快递员返回相应的数据给他
        List<EntrustResponse> result = new ArrayList<>();
        if (rule == UserContent.COURIER) {
            QueryWrapper<Entrust> queryWrapper = new QueryWrapper<>();
            queryWrapper.ne("entrust_status", "待取件");
            queryWrapper.eq("courier_id", user.getId()).or()
                    .eq("courier_id", 0);

            List<Entrust> entrusts = list(queryWrapper);
            safetyEntrust(result, entrusts);
            return result;
        }
        // 管理员 返回所有数据
        if (rule == UserContent.ADMINISTRATOR) {
            List<Entrust> entrusts = list();
            safetyEntrust(result, entrusts);
            return result;
        }
        // 用户返回相应的数据给他
        if (rule == UserContent.USER) {
            QueryWrapper<Entrust> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("u_id", user.getId());
            List<Entrust> entrusts = list(queryWrapper);
            safetyEntrust(result, entrusts);
            return result;
        }

        return result;
    }

    @Override
    public boolean updateEntrustOnce(Entrust entrust) {
        if (entrust == null || entrust.getId() <= 0)
            throw new BusinessException(ErrorCode.PARAM_ERROR, "该参数为空,或者该表单id不存在");
        return updateById(entrust);
    }

    private void safetyEntrust(List<EntrustResponse> result, List<Entrust> entrusts) {
        for (Entrust entrust : entrusts) {
            EntrustResponse temp = new EntrustResponse();
            temp.setId(entrust.getId());
            temp.setCourierId(entrust.getCourierId());
            temp.setNation(entrust.getNation());
            temp.setProvince(entrust.getProvince());
            temp.setCity(entrust.getCity());
            temp.setCounty(entrust.getCounty());
            temp.setDetailAdd(entrust.getDetailAdd());
            temp.setPostalCode(entrust.getPostalCode());
            temp.setConsigneeName(entrust.getConsigneeName());
            temp.setConsigneePhone(entrust.getConsigneePhone());
            temp.setShipperName(entrust.getShipperName());
            temp.setShipperPhone(entrust.getShipperPhone());
            temp.setCreateTime(entrust.getCreateTime());
            temp.setUpdateTime(entrust.getUpdateTime());
            temp.setEntrustStatus(entrust.getEntrustStatus());
            result.add(temp);
        }
    }

    @Override
    public int userRule(String token) {
        User user = RedisToken.readFromRedis(redisTemplate, token, User.class);
        if (user == null || user.getId() <= 0)
            return UserContent.NOT_LOGIN;
        if (user.getUserRole() == UserContent.ADMINISTRATOR)
            return UserContent.ADMINISTRATOR;
        if (user.getUserRole() == UserContent.USER)
            return UserContent.USER;
        if (user.getUserRole() == UserContent.COURIER)
            return UserContent.COURIER;
        throw new BusinessException(ErrorCode.PARAM_ERROR, "身份不明确");
    }

    @Override
    public boolean courierUpdateEntrust(CourierRequestBody courierRequestBody) {
        if (courierRequestBody == null || "".equals(courierRequestBody.getToken()))
            throw new BusinessException(ErrorCode.NO_AUTH, "该用户token无效");
        User user = RedisToken.readFromRedis(redisTemplate, courierRequestBody.getToken(), User.class);

        if (user == null || (user.getUserRole() != UserContent.ADMINISTRATOR
                && user.getUserRole() != UserContent.COURIER))
            throw new BusinessException(ErrorCode.NO_AUTH, "该用户无权限访问");

        // 修改邮件信息
        QueryWrapper<Entrust> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", courierRequestBody.getId());

        Entrust entrust = new Entrust();
        // 修改邮寄信息的状态与快递员账号id
        entrust.setEntrustStatus(courierRequestBody.getEntrustStatus());
        entrust.setCourierId(courierRequestBody.getCourierId());

        return update(entrust, queryWrapper);
    }

    @Override
    public boolean userComplete(CourierRequestBody requestBody) {
        if (requestBody == null || "".equals(requestBody.getToken()))
            throw new BusinessException(ErrorCode.NO_AUTH, "该用户token无效");
        User user = RedisToken.readFromRedis(redisTemplate, requestBody.getToken(), User.class);
        if (user == null || user.getId() == null || user.getId() == 0)
            throw new BusinessException(ErrorCode.NO_AUTH, "该用户token无效");

        Entrust entrust = getById(requestBody.getId());
        if (entrust == null)
            throw new BusinessException(ErrorCode.PARAM_ERROR, "未找到相符的寄件信息");

        if (Long.parseLong(user.getId().toString()) != entrust.getUId())
            throw new BusinessException(ErrorCode.NO_AUTH, "该用户无权限操作此条数据");
        updateById(entrust);
        return removeById(entrust.getId());
    }
}




